package com.zhku.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhku.entity.Appointable_list;
import com.zhku.entity.Appointment;
import com.zhku.entity.User;
import com.zhku.entity.Vaccinum;
import com.zhku.service.IAppointableListService;
import com.zhku.service.IAppointmentService;
import com.zhku.service.IUserService;
import com.zhku.service.IVaccinumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 疫苗预约 前端控制器
 * </p>
 *
 * @author dewey
 * @since 2023-03-31
 */
@RestController
@RequestMapping(value = "/appointment")
public class AppointmentController {
    // 预约记录
    @Autowired
    IAppointmentService appointmentService;

    @Autowired
    IAppointableListService appointableListService;

    @Autowired
    IUserService userService;

    @Autowired
    IVaccinumService vaccinumService;

    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * @description: 用来带参数，查询符合的预约信息
     * @author: deweyMDH
     * @param: [pageNum, pageSize, keyword]
     * @return: java.lang.String
     **/
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(
            @RequestParam(required = true, defaultValue = "1") Integer pageNum,
            @RequestParam(required = true, defaultValue = "1") Integer pageSize,
            @RequestParam(required = false, defaultValue = "") String keyword  //关键词
    ) throws JsonProcessingException {
        // 定义一个map来存放json的键值对
        Map result = new HashMap();
        //分页查询
        /* 分页构造函数
        Params:
        current – 当前页
        size – 每页显示条数*/

        //查询构造条件
        QueryWrapper<Appointment> queryWrapper = new QueryWrapper<>();
        // 成立的表达式，字段名 和 数值
        queryWrapper.like(keyword != null && !keyword.equals(""), "address", keyword);

        Page<Appointment> page = appointmentService.page(new Page<>(pageNum, pageSize), queryWrapper);
        page.getRecords().forEach(en -> {
            // 查询对应的用户和疫苗名称
            User user = userService.getById(en.getUserId());
            Vaccinum vaccinum = vaccinumService.getById(en.getVaccinumId());
            // 设置到预约信息中
            en.setUname(user.getName());
            en.setVname(vaccinum.getName());
        });

        // 在结果中放一个list集合
        result.put("list", page.getRecords());
        result.put("total", page.getTotal());
        // 返回json
        return objectMapper.writeValueAsString(result);
    }

    @RequestMapping(value = "/listAgrs")
    public String listAddress() throws JsonProcessingException {
        // 定义一个map来存放json的键值对
        Map result = new HashMap();
//        // 定义一个地点的 list
//        List address = new Vector<>();
//        //定义一个时间的 list
//        List time = new Vector<>();
        List<Appointable_list> applist = new LinkedList<>();

        List<Appointable_list> list = appointableListService.list();
        list = list.stream().filter(en -> {
            if (!applist.contains(en)) {
                applist.add(en);
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
        result.put("ok", true);
        result.put("address", list);

        // 返回json
        return objectMapper.writeValueAsString(result);
    }

    /**
     * @description: 查询医护人员
     * @author: deweyMDH
     * @param:
     * @return:
     **/
    @RequestMapping(value = "/listRole")
    public String listRole() throws JsonProcessingException {
        // 定义一个map来存放json的键值对
        Map result = new HashMap();
        List<User> users = new LinkedList<>();

        // 创建一个条件选择器，查医护人员
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.notIn("role", 0);
        wrapper.notIn("role", 1);
        List<User> list = userService.list(wrapper);
        list = list.stream().filter(en -> {
            if (!users.contains(en)) {
                users.add(en);
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
        result.put("ok", true);
        result.put("users", list);

        // 返回json
        return objectMapper.writeValueAsString(result);
    }

    @PostMapping(value = "/insert")
    public String insert(Appointment appointment) throws JsonProcessingException {
//         定义一个map来存放json的键值对
        Map result = new HashMap();
        boolean one = appointmentService.save(appointment);

        // 创建一个根据appointment，查找相应Appointable_list的条件选择器
        QueryWrapper<Appointable_list> wrapper = new QueryWrapper<>();
        wrapper.eq("vaccinum_id", appointment.getVaccinumId());
        wrapper.eq("address", appointment.getAddress());
        wrapper.eq("app_date", appointment.getAppDate());
        Appointable_list appointableList = appointableListService.getOne(wrapper);
        // 设置某场次，某时间的某种疫苗的预约数加一，剩余量-1
        appointableList.setAppNum(appointableList.getAppNum() + 1);
        appointableList.setNums(appointableList.getNums() - 1);
        // 修改预约列表的数据
        appointableListService.updateById(appointableList);
        //判断数据库是否有数据
        if (one != false) {
            result.put("ok", true);
            result.put("appointment", appointment);
        } else {
            result.put("ok", false);
            result.put("message", "错误");
        }
        // 返回
        return objectMapper.writeValueAsString(result);
    }

    @RequestMapping(value = "/update")
    public String updateAppointList(Long id) throws JsonProcessingException {
//         定义一个map来存放json的键值对
        Map result = new HashMap();

        Appointment one = appointmentService.getById(id);
        // 设置预约记录的状态为1
        Integer status = one.getStatus();
        if (status == 0){
            one.setStatus(1);
        } else if (status == 1){
            one.setStatus(0);
        }else {
            one.setStatus(1);
        }
        boolean two = appointmentService.updateById(one);
        //判断数据库是否有数据
        if (two != false) {
            result.put("ok", true);
            result.put("appointment", two);
        } else {
            result.put("ok", false);
            result.put("message", "接种修改错误");
        }
        // 返回
        return objectMapper.writeValueAsString(result);
    }


    /**
     * @description: 根据主键，删除相应的预约
     * @author: deweyMDH
     * @param: [Id]
     * @return: java.lang.String
     **/
    @DeleteMapping(value = "/delete/{id}")
    public String deleteAppointment(@PathVariable(value = "id") Integer Id) throws JsonProcessingException {
//         定义一个map来存放json的键值对
        Map result = new HashMap();

        boolean one = appointmentService.removeById(Id);
        //判断数据库是否有数据
        if (one != false) {
            result.put("ok", true);
            result.put("appointment", Id);
        } else {
            result.put("ok", false);
            result.put("message", "删除预约错误");
        }
        // 返回
        return objectMapper.writeValueAsString(result);
    }
}
